<template>
  <div class="data-table">
    <!-- 表格工具栏 -->
    <div v-if="showToolbar" class="table-toolbar">
      <t-space>
        <!-- 操作按钮 -->
        <t-button v-if="showAddButton" theme="primary" :icon="addIcon" @click="handleAdd">
          {{ addButtonText }}
        </t-button>
        
        <t-button 
          v-if="showDeleteButton" 
          theme="danger" 
          :icon="deleteIcon" 
          :disabled="!hasSelection"
          @click="handleDelete"
        >
          {{ deleteButtonText }}
        </t-button>
        
        <t-button 
          v-if="showExportButton" 
          theme="default" 
          :icon="exportIcon" 
          @click="handleExport"
        >
          {{ exportButtonText }}
        </t-button>
        
        <!-- 自定义工具栏插槽 -->
        <slot name="toolbar" />
      </t-space>
      
      <!-- 选中统计 -->
      <div v-if="showSelectionInfo && hasSelection" class="selection-info">
        已选中 {{ selectedRowKeys.length }} 项
      </div>
    </div>

    <!-- 表格主体 -->
    <t-table 
      ref="tableRef"
      row-key="id" 
      :data="data" 
      :columns="processedColumns" 
      :loading="loading"
      :bordered="bordered"
      :striped="striped"
      :pagination="pagination" 
      :selected-row-keys="selectedRowKeys" 
      vertical-align="top" 
      :hover="hover"
      @select-change="handleSelectChange"
      @page-change="handlePageChange"
    >
      <!-- 插槽支持 -->
      <template v-for="(_, slotName) in $slots" #[slotName]="slotProps">
        <slot :name="slotName" v-bind="slotProps" />
      </template>
      
      <!-- 空数据状态 -->
      <template #empty>
        <div class="empty-container">
          <t-icon name="file-search" size="48px" />
          <p class="empty-text">{{ emptyText }}</p>
        </div>
      </template>
    </t-table>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import type { PageInfo } from 'tdesign-vue-next'

// 表格列定义
interface TableColumn {
  colKey: string
  title: string
  width?: number
  fixed?: 'left' | 'right'
  type?: 'multiple' | 'single'
  ellipsis?: boolean
  sortable?: boolean
  filter?: {
    type: 'input' | 'select' | 'date' | 'date-range'
    options?: Array<{ label: string; value: any }>
  }
  [key: string]: any
}

// 表格操作按钮
interface TableAction {
  label: string
  type?: 'primary' | 'danger' | 'default'
  icon?: string
  handler: (row: any) => void
}

// Props
interface Props {
  // 数据相关
  data: any[]
  columns: TableColumn[]
  loading?: boolean
  
  // 表格样式
  bordered?: boolean
  striped?: boolean
  hover?: boolean
  
  // 分页相关
  pagination?: {
    current: number
    pageSize: number
    total: number
  }
  
  // 选择相关
  selectedRowKeys?: (string | number)[]
  
  // 工具栏配置
  showToolbar?: boolean
  showAddButton?: boolean
  showDeleteButton?: boolean
  showExportButton?: boolean
  showSelectionInfo?: boolean
  
  // 按钮文本
  addButtonText?: string
  deleteButtonText?: string
  exportButtonText?: string
  
  // 图标
  addIcon?: string
  deleteIcon?: string
  exportIcon?: string
  
  // 操作列配置
  showActions?: boolean
  actions?: TableAction[]
  actionColumnWidth?: number
  
  // 空数据文本
  emptyText?: string
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  bordered: true,
  striped: true,
  hover: true,
  pagination: () => ({
    current: 1,
    pageSize: 10,
    total: 0
  }),
  selectedRowKeys: () => [],
  showToolbar: true,
  showAddButton: false,
  showDeleteButton: false,
  showExportButton: false,
  showSelectionInfo: true,
  addButtonText: '新增',
  deleteButtonText: '删除',
  exportButtonText: '导出',
  addIcon: 'add',
  deleteIcon: 'delete',
  exportIcon: 'download',
  showActions: false,
  actions: () => [],
  actionColumnWidth: 120,
  emptyText: '暂无数据'
})

// Emits
const emit = defineEmits<{
  'select-change': [keys: (string | number)[]]
  'page-change': [pageInfo: PageInfo]
  'add': []
  'delete': [keys: (string | number)[]]
  'export': []
  'action-click': [action: TableAction, row: any]
}>()

// 计算属性
const hasSelection = computed(() => props.selectedRowKeys.length > 0)

// 处理后的列配置（自动添加操作列）
const processedColumns = computed(() => {
  const columns = [...props.columns]
  
  if (props.showActions && props.actions.length > 0) {
    columns.push({
      colKey: 'actions',
      title: '操作',
      width: props.actionColumnWidth,
      fixed: 'right'
    })
  }
  
  return columns
})

// 方法
const handleSelectChange = (keys: (string | number)[]) => {
  emit('select-change', keys)
}

const handlePageChange = (pageInfo: PageInfo) => {
  emit('page-change', pageInfo)
}

const handleAdd = () => {
  emit('add')
}

const handleDelete = () => {
  emit('delete', props.selectedRowKeys)
}

const handleExport = () => {
  emit('export')
}

const handleAction = (action: TableAction, row: any) => {
  emit('action-click', action, row)
}

// 暴露方法给父组件
defineExpose({
  clearSelection: () => {
    emit('select-change', [])
  },
  getSelectedRows: () => {
    return props.data.filter(item => 
      props.selectedRowKeys.includes(item.id)
    )
  },
  refresh: () => {
    // 触发刷新，可由父组件实现具体逻辑
    emit('page-change', props.pagination)
  }
})
</script>

<style lang="less" scoped>
.data-table {
  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .selection-info {
      color: var(--td-text-color-secondary);
      font-size: 14px;
    }
  }
  
  .empty-container {
    text-align: center;
    padding: 40px 0;
    
    .empty-text {
      margin-top: 16px;
      color: var(--td-text-color-secondary);
    }
  }
}
</style>